<template>
  <div>
    <n-modal
      :show="props.showModal"
      :on-mask-click="maskClick"
      :class="{ 'blow-up': isBlowUp }"
    >
      <n-card
        style="width: 50%; max-height: 60vh; min-width: 650px"
        :title="props.dialogTitle"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
        header-style="padding:20px;padding-bottom:10px;"
        content-style="overflow: hidden; overflow-y: auto;padding:20px;padding-top:0px;"
      >
        <template #header-extra>
          <n-button @click="closeModal" text size="tiny" color="#ff69b4">
            <template #icon>
              <n-icon size="20">
                <Close></Close>
              </n-icon>
            </template>
          </n-button>
        </template>
        <div style="margin: 20px 0px">
          <n-form
            label-placement="left"
            ref="formRef"
            :label-width="80"
            :model="formValue"
            :rules="rules"
          >
            <n-form-item label="用户名称" path="userName">
              <n-input
                v-model:value="formValue.userName"
                placeholder="请输入名称"
              />
            </n-form-item>
            <n-form-item label="用户账号" path="account">
              <n-input
                v-model:value="formValue.account"
                placeholder="请输入账号"
              />
            </n-form-item>
            <n-form-item label="用户密码" path="password">
              <n-input
                v-model:value="formValue.password"
                placeholder="请输入密码"
              />
            </n-form-item>
            <n-form-item label="用户角色" path="userRole">
              <n-select
                v-model:value="formValue.userRole"
                :options="roleOptions"
                label-field="name"
                value-field="id"
              />
            </n-form-item>
            <n-form-item label="头像图标" path="head">
              <n-upload
                v-model:value="formValue.head"
                accept="image/png, image/jpeg"
                list-type="image-card"
                :max="1"
                :default-upload="false"
                :show-file-list="true"
                ref="uploadRef"
                :on-before-upload="handleBeforeRead"
                file-list-style="width:80px;height:80px;"
                trigger-style="width:80px;height:80px;"
                :show-preview-button="false"
                width="50px;"
              >
                <n-icon
                  size="75"
                  v-if="formValue.head != '' && formValue.head != null"
                >
                  <img
                    :src="formValue.head"
                    style="width: 100%; height: 100%"
                    alt=""
                  />
                </n-icon>
              </n-upload>
            </n-form-item>
            <n-form-item label="是否可用">
              <n-switch v-model:value="formValue.enable" size="medium">
                <template #checked> 可用 </template>
                <template #unchecked>禁用 </template>
                <template #checked-icon>
                  <n-icon :component="CheckmarkDoneCircleSharp" />
                </template>
                <template #unchecked-icon>
                  <n-icon :component="CloseCircleOutline" />
                </template>
              </n-switch>
            </n-form-item>
          </n-form>
        </div>
        <template #action>
          <div
            style="
              margin: -15px;
              display: flex;
              justify-content: flex-end;
              gap: 10px;
            "
          >
            <n-button size="small" @click="closeModal">取消</n-button>
            <n-button size="small" type="primary" @click="handleValidateClick">
              确定
            </n-button>
          </div>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { createUserInfoRequest } from "@/models/platformModel";
import {
  createUser,
  getDefUserHead,
  getRoleAllList,
  updateUser,
  getUserById,
} from "@/api/platform";
import { Close } from "@vicons/ionicons5";

const props = defineProps({
  showModal: {
    type: Boolean,
    default: () => false,
  },
  data: {
    type: Array,
    default: "",
  },
  dialogTitle: {
    type: String,
    default: () => "创建用户",
  },
});
const formRef: any = ref(null);
const isBlowUp = ref(false);
const isUpdate = ref(false);
const roleOptions = ref<any>([]);
const formValue = ref<createUserInfoRequest & { id: String | null }>({
  id: null,
  account: null,
  password: null,
  userName: null,
  head: null,
  userRole: null,
  enable: true,
});
const rules = {
  userName: {
    required: true,
    trigger: ["blur", "input"],
    message: "请给用户一个名字",
  },
  account: {
    required: true,
    trigger: ["blur", "input"],
    message: "请给用户一个账号",
  },
  password: {
    required: true,
    trigger: ["blur", "input"],
    message: "请给用户一个密码",
  },
  userRole: {
    required: true,
    trigger: ["blur", "input"],
    message: "请给用户一个密码",
  },
};
const initFormValue = {
  id: null,
  account: null,
  password: null,
  userName: null,
  head: null,
  userRole: null,
  enable: true,
};

onMounted(() => [
  getRoleAllList().then((res) => {
    roleOptions.value = res.data;
  }),
]);

const init = (id: any = null) => {
  if (id != null) {
    isUpdate.value = true;
    getUserById({ id: id }).then((res) => {
      formValue.value = res.data;
    });
  } else {
    formValue.value = JSON.parse(JSON.stringify(initFormValue));

    getDefUserHead().then((res) => {
      formValue.value.head = res.data;
    });
  }
};

const maskClick = () => {
  isBlowUp.value = true;
  setTimeout(() => {
    isBlowUp.value = false;
  }, 500);
};
const emit = defineEmits(["closeModal", "getSysUserList"]);

// 假设你有一个方法来切换模态框的显示状态
const closeModal = () => {
  emit("closeModal");
};
const handleValidateClick = (e) => {
  e.preventDefault();
  formRef.value?.validate((errors) => {
    if (!errors) {
      if (!isUpdate.value) {
        createUser(formValue.value).then((res) => {
          if (res.code == 200) {
            window.$message.success(res.message);
            closeModal();
            emit("getSysUserList");
          } else {
            window.$message.error(res.message);
          }
        });
      } else {
        updateUser(formValue.value).then((res) => {
          if (res.code == 200) {
            window.$message.success(res.message);
            closeModal();
            emit("getSysUserList");
          } else {
            window.$message.error(res.message);
          }
        });
      }
    } else {
      console.log(formValue.value);
      window.$message.error("表单验证错误");
    }
  });
};
const handleBeforeRead = async ({ file }: any) => {
  // 创建 FileReader 对象
  const reader: any = new FileReader();
  console.log(file);
  reader.onload = () => {
    const blobUrl = reader.result as string;
    // console.log(blobUrl);
    // 将读取结果转换为 Base64 格式并进行处理
    const base64Data = reader.result.split(",")[1]; // 获取 base64 数据部分
    // 进行后续处理，比如发送到服务器等
    formValue.value.head = "data:image/png;base64," + base64Data;
    file.file.url = blobUrl;
  };

  // 读取文件并转换为 Data URL
  reader.readAsDataURL(file.file);
  // 你可以决定是否继续上传，返回true则继续，返回false则取消上传
  return false;
};
defineExpose({ init });
</script>

<style scoped>
.blow-up {
  animation: scaleAnimation 0.5s infinite;
  transform-origin: center center;
  /* 设置缩放中心为元素中心点 */
}

@keyframes scaleAnimation {
  0% {
    transform: scale(1);
    transform-origin: center center;
  }

  50% {
    transform: scale(1.1);
    /* 在动画中点缩放到1.1倍 */
    transform-origin: center center;
  }

  100% {
    transform: scale(1);
    /* 在动画结束时缩放回原始大小 */
    transform-origin: center center;
  }
}
</style>
